import { useState, useCallback, useEffect } from 'react'
import Browser from 'webextension-polyfill'
// import useSWRImmutable from 'swr/immutable'
import { SearchEngine } from './search-engine-configs'
import { TriggerMode } from '../config'
import ChatGPTCard from './ChatGPTCard'
import { QueryStatus } from './ChatGPTQuery'
import { getSearchParam, copyTranscript, getConverTranscript } from './utils'
import {
  GearIcon,
  CheckIcon,
  CopyIcon,
  ChevronDownIcon,
  ChevronUpIcon,
  AlertIcon,
} from '@primer/octicons-react'
import { queryParam } from 'gb-url'

interface Props {
  question: string
  transcript?: any
  triggerMode: TriggerMode
  siteConfig: SearchEngine
  langOptionsWithLink?: any
}

function ChatGPTContainer(props: Props) {
  const [queryStatus, setQueryStatus] = useState<QueryStatus>()
  const { question, transcript, triggerMode, siteConfig, langOptionsWithLink } = props
  const [copied, setCopied] = useState(false)
  const [transcriptShow, setTranscriptShow] = useState(false)
  const [currentTranscript, setCurrentTranscript] = useState(transcript)
  const [selectedOption, setSelectedOption] = useState(0)

  const handleChange = async (event) => {
    const val = event.target.value || ''
    const videoId = queryParam('v', window.location.href || '')

    if (val < 0 || !videoId) {
      return
    }

    setSelectedOption(val)

    const transcriptList = await getConverTranscript({ langOptionsWithLink, videoId, index: val })

    setTranscriptShow(true)

    setCurrentTranscript(transcriptList)
  }

  const copytSubtitle = () => {
    const videoId = getSearchParam(window.location.href)?.v
    copyTranscript(videoId, currentTranscript)
    setCopied(true)
  }

  const openOptionsPage = useCallback(() => {
    Browser.runtime.sendMessage({ type: 'OPEN_OPTIONS_PAGE' })
  }, [])

  useEffect(() => {
    if (copied) {
      const timer = setTimeout(() => {
        setCopied(false)
      }, 500)
      return () => clearTimeout(timer)
    }
  }, [copied])

  const switchtranscriptShow = () => {
    setTranscriptShow((state) => !state)
  }

  return (
    <>
      <div className="glarity--chatgpt">
        <div className="glarity--header">
          <div className="x">
            <a
              href="https://glarity.app"
              rel="noreferrer"
              target="_blank"
              className="glarity--header__logo"
            >
              <img
                src=""
                alt="Glarity"
              />
              Glarity Summary
            </a>
            <a href="javascript:;" className="glarity--header__logo" onClick={openOptionsPage}>
              <GearIcon size={14} />
            </a>
          </div>

          <div className="glarity--chatgpt__action"></div>
        </div>

        <div className="glarity--main">
          <div className="glarity--main__container">
            {question ? (
              <>
                <ChatGPTCard
                  question={question}
                  triggerMode={triggerMode}
                  onStatusChange={setQueryStatus}
                />
              </>
            ) : siteConfig?.name === 'youtube' ? (
              <>
                <p>No Transcription Available... </p>
                <p>
                  Try{' '}
                  <a
                    href="https://huggingface.co/spaces/jeffistyping/Youtube-Whisperer"
                    rel="noreferrer"
                    target="_blank"
                  >
                    Youtube Whisperer
                  </a>{' '}
                  to transcribe!
                </p>
              </>
            ) : (
              <p>
                <AlertIcon size={14} /> No results.
              </p>
            )}
          </div>
        </div>

        {question && currentTranscript && (
          <div className="glarity--main">
            <div className="glarity--main__header">
              <div className="glarity--main__header--title">
                Transcript
                {langOptionsWithLink.length > 1 && (
                  <>
                    {' '}
                    <select
                      className="glarity--select"
                      value={selectedOption}
                      onChange={handleChange}
                    >
                      {langOptionsWithLink &&
                        Array.from(langOptionsWithLink).map((v, i) => {
                          return (
                            <option key={i} value={i}>
                              {v.language}
                            </option>
                          )
                        })}
                    </select>
                  </>
                )}
              </div>
              <div className="glarity--main__header--action">
                <a href="javascript:;" onClick={copytSubtitle}>
                  {copied ? <CheckIcon size={14} /> : <CopyIcon size={14} />}
                </a>

                <a href="javascript:;" onClick={switchtranscriptShow}>
                  {transcriptShow ? <ChevronUpIcon size={16} /> : <ChevronDownIcon size={16} />}
                </a>
              </div>
            </div>

            <div
              className="glarity--main__container glarity--main__container--subtitle"
              style={{
                display: transcriptShow ? 'block' : 'none',
              }}
            >
              {currentTranscript.map((v, i) => {
                const { time, text } = v

                return (
                  <div className="glarity--subtitle" key={i}>
                    <div className="subtitle--time">{time}</div>
                    <div
                      className="subtitle--text"
                      dangerouslySetInnerHTML={{ __html: text }}
                    ></div>
                  </div>
                )
              })}
            </div>
          </div>
        )}
      </div>
    </>
  )
}

export default ChatGPTContainer
